import { Inject, Provide } from '@midwayjs/core'
import { deleteLogByIdReq, getLogByDayReq, getLogListDto, saveLogReq } from '../dto/all-dto'
import { apiResponse, ResPageData } from '../apiResponse'
import { DayLog } from '../entity/day_log.entity'
import { Repository } from 'typeorm'
import dayjs = require('dayjs')
import { InjectEntityModel, TypeORMDataSourceManager } from '@midwayjs/typeorm'

@Provide()
export class DayLogService {
  @Inject()
  dataSourceManager: TypeORMDataSourceManager

  @InjectEntityModel(DayLog)
  dayLogModel: Repository<DayLog>

  constructor() {}

  // 保存日志
  async saveLog(body: saveLogReq) {
    let entity: DayLog
    if (body.id != undefined) {
      entity = await this.dayLogModel.findOne({
        where: {
          id: body.id,
        },
      })
      if (entity == null) {
        return apiResponse.error('根据ID查询不到信息')
      }
    } else {
      entity = await this.dayLogModel.findOne({
        where: {
          day: body.day,
          type: body.type,
        },
      })
    }
    if (entity == null) {
      // 创建
      entity = new DayLog()
      entity.day = body.day
      entity.type = body.type
      entity.content = body.content
    } else {
      // 修改
      entity.day = body.day
      entity.type = body.type
      entity.content = body.content
    }
    await this.dayLogModel.save(entity)
    return apiResponse.success({ id: entity.id })
  }

  // 根据日期和类型查询日志详细信息
  async getLogByDay(body: getLogByDayReq) {
    let entity = await this.dayLogModel.findOne({
      where: {
        day: body.day,
        type: body.type,
      },
    })
    return apiResponse.success(entity)
  }

  // 删除日志信息
  async deleteById(body: deleteLogByIdReq) {
    await this.dayLogModel.update(body.id, { isDel: 1 })
    return apiResponse.success()
  }

  // 获取日志分页
  async getLogList(body: getLogListDto) {
    const query = this.dayLogModel.manager.createQueryBuilder()
    query.from(DayLog, 'a')
    query.where(`a.isDel = 0`)

    if (body.startDate != undefined)
      query.andWhere('a.day >= :beginAt', { beginAt: dayjs(body.startDate).format('YYYY-MM-DD') })

    if (body.endDate != undefined)
      query.andWhere('a.day <= :endAt', { endAt: dayjs(body.endDate).format('YYYY-MM-DD') })

    if (body.type != undefined) query.andWhere('a.type = :type', { type: body.type })

    query.orderBy('a.day', 'DESC')
    query.offset((body.pageNo - 1) * body.pageSize)
    query.limit(body.pageSize)
    query.select('a.*')
    const count = await query.getCount()
    const list = await query.getRawMany()

    const outJson: ResPageData = new ResPageData()
    outJson.pageTotal = Math.ceil(count / body.pageSize)
    outJson.itemTotal = count
    outJson.pageTotal = body.pageNo
    outJson.pageSize = body.pageSize
    outJson.items = list

    return apiResponse.success(outJson)
  }
}
